﻿(function($) {
    var methods = {
        init: function(options) {
            return this.each(function() {
                var el = $(this);
                if ($(this).data('dialog'))
                    return;

                var Data = {
                    TemplateId: options.templateId,
                    Template: null
                };

                setTemplate($(this), Data, options.templateId);

                $(this).data('dialog', Data);

                $(window).bind("hashchange", function() {
                    if (el.attr('visible') == 'visible')
                        if (location.hash.indexOf('.' + el.attr('class').split(' ')[0]) < 0)
                            el.dialog('hide');
                });
            });
        },
        show: function(data) {
            var el = $(this);
            var d = el.data('dialog');
            if (!d)
                return;

            var html = d.Template(data);
            el.html(html);
            el.find('.action').click(function(e) {
                if (!data.Buttons)
                    return Event.stopEvent(e);
                var index = $(this).parent().children().index($(this));
                if (index >= data.Buttons.length)
                    return;
                var button = data.Buttons[index];
                if (button && button.Callback)
                    button.Callback();

                return Event.stopEvent(e);
            });

            location.hash = el.selector;
            el.show().css({
                'margin-left': -(el.outerWidth() / 2) + 'px',
                'margin-top': -(el.outerHeight() / 2) + 'px'
            });
            el.trigger('onShow');
            el.attr('visible', 'visible');
            el.attr("tabindex", -1).focus();
        },
        hide: function() {
            var el = $(this);
            el.empty().hide();
            el.trigger('onHide');
            el.removeAttr('visible');
        },
        option: function(key, value) {
            var data = $(this).data('dialog');
            if (!data)
                return;

            if (key == 'templateId')
                setTemplate($(this), data, value);
        }
    };

    var setTemplate = function(el, data, templateId) {
        data.TemplateId = templateId;
        data.Template = Handlebars.compile($("#" + templateId).html());
    };

    $.fn.dialog = function(method) {
        if (methods[method])
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        else if (typeof method === 'object' || !method)
            return methods.init.apply(this, arguments);
    };
})(jQuery);